//
//  HistogramView.m
//  AirQuality
//
//  Created by Mac on 15/12/29.
//  Copyright © 2015年 Po. All rights reserved.
//

#import "HistogramView.h"
#import "CollectionViewCell.h"
#import "DrayImage.h"
#import "BorederView.h"

@interface HistogramView ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIScrollViewDelegate>

@property (strong, nonatomic) UICollectionView * collectionView;
@property (strong, nonatomic) UISegmentedControl * segment;
@property (strong, nonatomic) NSArray * dataArr;
@property (strong, nonatomic) NSString * max,* dayMax,* hourMax;
@property (strong, nonatomic) UIScrollView * scrollView;
@property (strong, nonatomic) UIView * instructionView;  //提示框
@property (strong, nonatomic) DrayImage * triangleImage; //三角形
//@property (strong, nonatomic) BorederView * borderView;   //边框
@property (strong, nonatomic) NSMutableArray * allDataArr , * allTimeArr; //所有数据
@property (strong, nonatomic) UICollectionViewFlowLayout *flowLayout;
@property (strong, nonatomic) NSArray * dayArr, * dataSouce;
@property (strong, nonatomic) UILabel * countLable;
@property (strong, nonatomic)  NSString * key;
@property (assign) CGFloat widthOff,dayOff,hourOff;
@property (assign) NSInteger flag,isFirstTap,dayScroll;
@property (strong, nonatomic) UIView * lastView, * twoView, *horizontalView;                         // 矩形框
@property (assign) CGFloat allWidth;        //矩形框移动距离
@property (strong, nonatomic) NSMutableArray * viewArray ,* indexArray;  //存柱状图
@property (assign,nonatomic) NSInteger test;
@property(assign)  CGFloat lastPosition ;
@property (strong, nonatomic) NSMutableDictionary * viewDic;
@property (strong, nonatomic) NSArray * allKeyArr;
@property (strong, nonatomic) NSMutableArray * firstHistog;
@property (assign) NSInteger distance;
@property (strong, nonatomic) NSString * rightString ;
@end

@implementation HistogramView

- (instancetype)initWithFrame:(CGRect)frame withData:(NSDictionary *)data withDayArr:(NSDictionary *)dayArr
{
    if ([super initWithFrame:frame]) {
        _max = data[@"max"];
        _hourMax = data[@"max"];
        NSArray * keyarray = [data allKeys];
        _dayArr = [dayArr allValues];
        _allWidth = 0;
        _viewArray = [NSMutableArray array];
        _indexArray = [NSMutableArray array];
        _viewDic = [NSMutableDictionary dictionary];
        _firstHistog = [NSMutableArray array];
        _allKeyArr = [NSArray array];
        _allDataArr = [NSMutableArray array];
        _allTimeArr = [NSMutableArray array];
        for (NSString * string in keyarray) {
            if (![string isEqualToString:@"max"]) {
                _key = string;
            }
        }
        _dataArr = data[_key];
        _dayMax = [[dayArr allKeys] firstObject];
        if ([RJUserData defaultRJUserData].isDayData) {
           _dataSouce = _dataArr;
            if (!_dataSouce) {
                return nil;
            }
        }else{
            _isFirstTap = YES;
            _max = [[dayArr allKeys] firstObject];
            _dataSouce = _dayArr[0];
            if (!_dataSouce) {
                return nil;
            }
        }
        self.backgroundColor = [UIColor whiteColor];
         [self integrationData];
        [self getSwitchView];
        [self getTriangleImageWithFram:CGRectMake(ScreenWidth-29, 160, 30, 30)];
        if ([_key isEqualToString:@"AQI"]) {
            [self getinstructionViewWithFrame:CGRectMake(ScreenWidth-185+15+10, 170, 180-25, 16)];
        }else{
        [self getinstructionViewWithFrame:CGRectMake(ScreenWidth-185, 170, 180, 16)];
        }
           NSLog(@"%@",_key);
//        [self getScrollView];
    }
    return self;
}


- (void)initailizeCollection
{
    _flowLayout= [[UICollectionViewFlowLayout alloc] init];
    _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;//滚动方向
    _flowLayout.minimumLineSpacing = -0.0;//行间距(最小值)
    _flowLayout.minimumInteritemSpacing = 1.0;//item间距(最小值)
    _flowLayout.itemSize = CGSizeMake(6, 120);//item的大小
   _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 200) collectionViewLayout:_flowLayout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    [_collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"HistogramCell"];
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    self.collectionView.alwaysBounceVertical = NO;
    self.collectionView.alwaysBounceHorizontal = NO;
    [self addSubview:_collectionView];
    [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_allDataArr.count-50 inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    if ([RJUserData defaultRJUserData].isDayData) {
        [self getAllHourOffset];
    }else{
        [self getAllYearOffset];
    }
}

- (void)getSwitchView
{
    if (!_segment) {
        NSArray * segArr = @[@"小时数据",@"日数据"];
        _segment = [[UISegmentedControl alloc] initWithItems:segArr];
        _segment.frame = CGRectMake(100, 10, ScreenWidth-200, 20);
        if ([RJUserData defaultRJUserData].isDayData) {
            _segment.selectedSegmentIndex = 0;
        }else{
            _segment.selectedSegmentIndex = 1;
        }
        _segment.momentary = NO;
        _segment.tintColor = SysMainColor;
        [_segment addTarget:self action:@selector(segChange:) forControlEvents:UIControlEventValueChanged];
        [self addSubview:_segment];
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{

    return _allDataArr.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
   
  CollectionViewCell * cell = (CollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"HistogramCell" forIndexPath:indexPath];
    for (UIView * view in [cell.contentView subviews]) {
        [view removeFromSuperview];
    }
    if (_isFirstTap) {
        _max = _dayMax;
    }else{
        _max = _hourMax;
    }
    [_firstHistog addObject:[NSString stringWithFormat:@"%ld", (long)indexPath.row]];
    NSDictionary * exchangeDic = @{@"AQI":@"AQI",@"PM2.5":@"PM2_5",@"PM₁₀":@"PM10",@"O₃":@"O3",@"SO₂":@"SO2",@"NO₂":@"NO2",@"CO":@"CO"};
    NSString * type = exchangeDic[_key];
        if (indexPath.row == _allDataArr.count-1) {
            if (!_test) {
                NSString * firstDis = [_firstHistog firstObject];
                NSString * lastDic = [_firstHistog lastObject];
                _distance =[lastDic integerValue]- [firstDis integerValue];
                [self setCountLableCount:_allDataArr.count-5];
                _test = YES;
                 _flag ++;
                if (_flag == 1) {
                  _widthOff = _collectionView.contentOffset.x-4;
                }
            }
        return cell;
    }
    CGFloat count = 100.0/[_max floatValue];
    CGFloat hight = [_allDataArr[indexPath.row] floatValue]*count;
    if (isnan(hight)) {
        hight = 0.0;
    }
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0.5, 120-hight, 5.5, hight)];
//     NSLog(@"%ld,%ld",indexPath.row,_allDataArr.count);
//    if (indexPath.row == _allDataArr.count-2) {
//        view.layer.borderColor = [UIColor grayColor].CGColor;
//        view.layer.borderWidth = 2.0;
//        _lastView = view;
//        return cell;
//    }
    CGFloat value = [_allDataArr[indexPath.row] floatValue];
    view.backgroundColor = [RJTools getColorWithAirNum:value  type:type alpha:1];
    _allKeyArr = [_viewDic allKeys];
    NSString * keySring = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
    if ([_allKeyArr indexOfObject:keySring]) {
       [_viewDic setObject:view forKey:keySring];
    }
    
    [cell.contentView addSubview:view];
    NSString * viewKey = [NSString stringWithFormat:@"%d",indexPath.row+_distance-3];
    if (_rightString && [_rightString integerValue]-indexPath.row != 1) {
        _lastView.layer.borderWidth = 0.0;
        NSString * string = [NSString stringWithFormat:@"%d",indexPath.row-3];
        UIView * grayView = _viewDic[string];
        _rightString = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
        grayView.layer.borderColor = [UIColor grayColor].CGColor;
        grayView.layer.borderWidth = 2.0;
        _lastView = grayView;
         _triangleImage.frame = CGRectMake(ScreenWidth-29+4, 160, 30, 30);
        [self setCountLableCount:[string integerValue]];
        return cell;
    }
        if ([_allKeyArr indexOfObject:viewKey]) {
            if (DeviceType > 6) {
                _triangleImage.frame = CGRectMake(ScreenWidth-29-2, 160, 30, 30);
            }else if (DeviceType > 5.5){
                _triangleImage.frame = CGRectMake(ScreenWidth-29+2, 160, 30, 30);
            }else{
                _triangleImage.frame = CGRectMake(ScreenWidth-29+4, 160, 30, 30);
            }
            _lastView.layer.borderWidth = 0.0;
            UIView * grayView = _viewDic[viewKey];
            _rightString = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
            grayView.layer.borderColor = [UIColor grayColor].CGColor;
            grayView.layer.borderWidth = 2.0;
            _lastView = grayView;
            [self setCountLableCount:[viewKey integerValue]];
        }
    return cell;
}

#pragma mark --getinstructionView
- (void)getinstructionViewWithFrame:(CGRect)frame
{
    if (!_instructionView) {
        _instructionView = [[UIView alloc] initWithFrame:frame];
        _instructionView.backgroundColor = SysMainColor;
        _instructionView.layer.cornerRadius = 4.0;
        _instructionView.layer.masksToBounds = YES;
        _countLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 180, 17)];
        _countLable.font = [UIFont systemFontOfSize:10];
        _countLable.textColor = [UIColor whiteColor];
        [_instructionView addSubview:_countLable];
        [self addSubview:_instructionView];
        UIView * topLine = [[UIView alloc] initWithFrame:CGRectMake(0, 50, ScreenWidth, 1)];
        topLine.backgroundColor = [UIColor grayColor];
        [self addSubview:topLine];
        UIView * bottomLine = [[UIView alloc] initWithFrame:CGRectMake(0, 160, ScreenWidth, 1)];
        bottomLine.backgroundColor = [UIColor grayColor];
        [self addSubview:bottomLine];
    }
}

- (void)setCountLableCount:(NSInteger)count
{
//    NSLog(@"---%ld,%ld",count,_allTimeArr.count);
    if (count > _allDataArr.count || count < 0) {
        return;
    }
    NSString * string;
    if ([_key isEqualToString:@"PM2.5"]) {
        string = @"PM₂.₅";
    }else{
        string = [NSString stringWithFormat:@"  %@",_key];
    }
    if ([_key isEqualToString:@"AQI"]) {
        _countLable.text = [NSString stringWithFormat:@"%@%@%@%@",_allTimeArr[count],string,@"=",_allDataArr[count]];
    }else if ([_key isEqualToString:@"CO"]){
        _countLable.text = [NSString stringWithFormat:@"%@%@%@%@%@",_allTimeArr[count],string,@"=",_allDataArr[count],@"mg/m³"];
    }else{
        _countLable.text = [NSString stringWithFormat:@"%@%@%@%@%@",_allTimeArr[count],string,@"=",_allDataArr[count],@"µg/m³"];
    }
}

- (void)getTriangleImageWithFram:(CGRect)frame
{
    if (!_triangleImage) {
        _triangleImage = [[DrayImage alloc] initWithFrame:frame];
        _triangleImage.backgroundColor = [UIColor clearColor];
        [self addSubview:_triangleImage];
    }
}

- (void)integrationData
{
    if (!_dataSouce) {
        return;
    }
    NSInteger count ;
    if (DeviceType > 6) {
        count = 65;
    }else if (DeviceType > 5.5){
        count = 59;
    }else if (DeviceType > 5){
        count = 50;
    }else{
        count = 50;
    }

    for (NSInteger i = 0; i < count; i ++) {
        [_allTimeArr addObject:@"0"];
        [_allDataArr addObject:@"0"];
    }
    for (NSUInteger i = 0; i < _dataSouce.count; i ++) {
        if (i%2 == 0) {
            NSArray * arr = _dataSouce[i];
            for (NSString * string in arr) {
                [_allTimeArr addObject:string];
                NSString * timeStr = _allTimeArr[i];
                NSString * subStr = [timeStr substringWithRange:NSMakeRange(timeStr.length-4, 4)];
                if ([subStr isEqualToString:@"0:00"]) {
                    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(i*6, 60, 1, 140)];
                    view.backgroundColor = [UIColor grayColor];
                    [_collectionView addSubview:view];
                }
                
            }
        }else{
            NSArray * arr = _dataSouce[i];
            for (NSString * string in arr) {
                if ([_key isEqualToString:@"CO"]) {
                    float value = [string floatValue];
                   [_allDataArr addObject:[NSString stringWithFormat:@"%.1f",value]];
                }else{
                   [_allDataArr addObject:string];
                }
            }
        }
    }
    NSString * string;
    if ([_key isEqualToString:@"PM2.5"]) {
      string = @"PM₂.₅";
    }else{
      string = [NSString stringWithFormat:@"  %@",_key];
    }
    
    if ([_key isEqualToString:@"AQI"]) {
      _countLable.text = [NSString stringWithFormat:@"%@%@%@%@",_allTimeArr[0],string,@"=",_allDataArr[0]];
    }else if ([_key isEqualToString:@"CO"]){
        _countLable.text = [NSString stringWithFormat:@"%@%@%@%@%@",_allTimeArr[0],string,@"=",_allDataArr[0],@"mg/m³"];
    }else{
        _countLable.text = [NSString stringWithFormat:@"%@%@%@%@%@",_allTimeArr[0],string,@"=",_allDataArr[0],@"µg/m³"];
    }
    for (NSInteger i = 0; i < 4; i ++) {
        [_allTimeArr addObject:@"0"];
        [_allDataArr addObject:@"0"];
    }
    [self initailizeCollection];
}

- (void)segChange:(UISegmentedControl *)sender
{
    if (sender.selectedSegmentIndex == 1) {
        _isFirstTap = YES;
        _dataSouce = _dayArr[0];
        [RJUserData defaultRJUserData].isDayData = NO;
        if (_delegate) {
            [_delegate isChange:YES withKey:_key];
        }
    }else if (sender.selectedSegmentIndex == 0){
        _isFirstTap = NO;
        _dataSouce = _dataArr;
        [RJUserData defaultRJUserData].isDayData = YES;
        if (_delegate) {
            [_delegate isChange:YES withKey:_key];
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
   
    CGFloat width = _widthOff - scrollView.contentOffset.x;
 
    if (_flag >= 1) {
        if (width < 0 ) {
            [_collectionView setContentOffset:CGPointMake(_widthOff, 0)];
        }
    }

}

- (void)getAllHourOffset
{
    
    for (NSInteger i = 0; i < _allTimeArr.count; i ++) {
        NSString * timeStr = _allTimeArr[i];
        NSString * subStr = [timeStr substringWithRange:NSMakeRange(timeStr.length-5, 5)];
        if ([subStr isEqualToString:@"00:00"]) {
            UIView * view = [[UIView alloc] initWithFrame:CGRectMake(i*6, 50, 1, 110)];
            view.backgroundColor = [UIColor grayColor];
            [_collectionView addSubview:view];
            UILabel * timeLable = [[UILabel alloc] initWithFrame:CGRectMake(i*6, 50, 80, 20)];
            NSString * lableStr = [timeStr substringToIndex:10];
            timeLable.text = lableStr;
            timeLable.font = [UIFont systemFontOfSize:12];
            [_collectionView addSubview:timeLable];
        }
    }

}

- (void)getAllYearOffset
{
    for (NSInteger i = 0; i < _allTimeArr.count; i ++){
        NSString * timeStr = _allTimeArr[i];
       NSString * subStr = [timeStr substringWithRange:NSMakeRange(timeStr.length-2, 2)];
        if ([subStr isEqualToString:@"01"]) {
            UIView * view = [[UIView alloc] initWithFrame:CGRectMake(i*6, 50, 1, 110)];
            view.backgroundColor = [UIColor grayColor];
            [_collectionView addSubview:view];
            UILabel * timeLable = [[UILabel alloc] initWithFrame:CGRectMake(i*6, 50, 80, 20)];
            NSString * lableStr = [timeStr substringToIndex:10];
            timeLable.text = lableStr;
            timeLable.font = [UIFont systemFontOfSize:12];
            [_collectionView addSubview:timeLable];
        }

    }
}
@end
